package com.ouheng.common.utils;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

/**
 * 导出excel表配置
 * ClassName: ExportExcel 
 * @Description: TODO
 * @author zhanghui
 * @date 2018年7月13日
 */
public class ExportExcel {

	/**
	 * 
	 * @Title: ExportExcel   
	 * @Description: TODO(这里用一句话描述这个方法的作用)   
	 * @param: @param headers 表头信息
	 * @param: @param workbook
	 * @param: @param sheet
	 * @param: @param fileName 文件名称
	 * @param: @param request
	 * @param: @param response
	 * @param: @throws IOException      
	 * @return: void      
	 * @throws
	 */
	public static void ExportExcel(String[] headers,HSSFWorkbook workbook,HSSFSheet sheet,String fileName,HttpServletRequest request,HttpServletResponse response)throws IOException{
		//处理文件名称乱码
		String agent = request.getHeader("USER-AGENT").toLowerCase();
		response.setContentType("application/vnd.ms-excel");
		String codedFileName = java.net.URLEncoder.encode(fileName, "UTF-8");
		if (agent.contains("firefox")) {
			response.setCharacterEncoding("utf-8");
			response.setHeader("content-disposition", "attachment;filename=" + new String(fileName.getBytes(), "ISO8859-1") + ".xls" );
		} else {
			response.setHeader("content-disposition", "attachment;filename=" + codedFileName + ".xls");
		}
		   
		HSSFRow row = sheet.createRow(0);
		row.setHeightInPoints(20);
		HSSFCellStyle cellStyle = workbook.createCellStyle();  //创建设置EXCEL表格样式对象 cellStyle
		// 一、设置背景色:
		cellStyle.setFillForegroundColor((short) 13);// 设置背景色  
		cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); 
		
		//二、设置边框:
		cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框  
		cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框  
		cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框  
		cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框  
		
		//三、设置居中:
		cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 水平居中  
		cellStyle.setAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直居中  
		cellStyle.setAlignment(HSSFCellStyle.VERTICAL_BOTTOM);//垂直底部  
		cellStyle.setAlignment(HSSFCellStyle.VERTICAL_TOP);//垂直顶部 
		
		HSSFFont font = workbook.createFont();  
		font.setFontName("宋体");  
		font.setFontHeightInPoints((short) 12);//设置字体大小   
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//粗体显示
		cellStyle.setFont(font);//选择创建的字体格式 
		
		//在excel表中添加表头
		for(int i=0;i<headers.length;i++){
		    HSSFCell cell = row.createCell(i);
		    HSSFRichTextString text = new HSSFRichTextString(headers[i]);
		    cell.setCellValue(text);
		}
	}
}
